package com.zhuimeng.Application.utils;

import com.zhuimeng.Application.entity.Player;
import com.zhuimeng.Application.entity.Room;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RoomMangerUtils {

    private static Map<Integer, Room> roomMap = new ConcurrentHashMap<>();
    private static Map<Session, Room> sessionRoomMap = new ConcurrentHashMap<>();


    public static void putRoom(Integer rid, Room room) {
        roomMap.put(rid, room);
    }

    public static void putRoom(Session session, Room room) {
        sessionRoomMap.put(session, room);
    }

    public static Room getRoom(Integer rid) {
        return roomMap.get(rid);
    }

    public static Room getRoom(Session session) {
        return sessionRoomMap.get(session);
    }

    public static void removeRoom(Integer roomId) {
        Room room = roomMap.remove(roomId);
        if (room != null) {
            Session session1 = room.getPlayer1().getSession();
            Session session2 = room.getPlayer2().getSession();

            sessionRoomMap.remove(session1);
            sessionRoomMap.remove(session2);
        }
    }

    public static void removeRoom(Session session) {
        Player otherPlayer = null;
        Room room = sessionRoomMap.remove(session);
        if(room.getOtherPlayer(session)!=null){
            otherPlayer = room.getOtherPlayer(session);
        }
        if (room != null) {
            roomMap.remove(room.getRoomId());
            if (otherPlayer != null) {
                Session otherSession = room.getOtherPlayer(session).getSession();
                sessionRoomMap.remove(otherSession);
            }
        }
    }

    public static List<Room> getRoomList() {
        return new ArrayList<>(roomMap.values());
    }

}
